package ua.edu.nuos.jeetraining2012.automator.services.common.api.dao.http;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Parse json response from post/get request
 * @author Timur Yarosh
 *         Date: 03.06.13
 *         Time: 23:30
 */
public class JsonHttpClient {
    private static final String ENCODING = "UTF-8";
    public static JSONObject post(String url, List<NameValuePair> params) throws IOException, ParseException {
        HttpPost request = new HttpPost(url);
        request.setEntity(new UrlEncodedFormEntity(params, ENCODING));
        String responseBody = executePostRequest(request);
        return (JSONObject) new JSONParser().parse(responseBody);
    }

    public static JSONObject get(String url) throws IOException, ParseException {
        HttpGet request = new HttpGet(url);
        String responseBody = executeGetRequest(request);
        return (JSONObject) new JSONParser().parse(responseBody);
    }

    private static String executeGetRequest(HttpGet request) throws IOException {
        StringBuilder responseBody = new StringBuilder();
        String buffer;
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(request);
        InputStream content = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        while ((buffer = reader.readLine()) != null) {
            responseBody.append(buffer);
        }
        return responseBody.toString();
    }

    private static String executePostRequest(HttpPost request) throws IOException {
        StringBuilder responseBody = new StringBuilder();
        String buffer;
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(request);
        InputStream content = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        while ((buffer = reader.readLine()) != null) {
            responseBody.append(buffer);
        }
        return responseBody.toString();
    }
}
